package com.lottery.system.service.impl;

import com.lottery.system.common.errorcode.ServiceErrorCodeConstants;
import com.lottery.system.common.exception.ServiceException;
import com.lottery.system.common.utils.*;
import com.lottery.system.service.VerificationCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: xiaoxie
 * create: 2024-09-04 11:29
 * @BelongsProject: lottery-system
 * @BelongsPackage: com.lottery.system.service.impl
 * description: 验证码实现类
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private final static Logger logger = LoggerFactory.getLogger(VerificationCodeServiceImpl.class);
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SMSUtil smsUtil;
    //存储在redis的前缀封装,其他的公用同一个key
    private final static String VERIFICATION_CODE_PREFIX = "verificationCode:";
    //过期时间
    private final static Long VERIFICATION_CODE_TIMEOUT = 60L;
    //短信模板号
    private final static String VERIFICATION_TEMPLATE_CODE = "SMS_472315385";
    @Override
    public void setVerificationCode(String phoneNumber) {

        //校验手机号是否有效
        if(!RegexUtil.checkMobile(phoneNumber)) {
            logger.error(ServiceErrorCodeConstants.PASSWORD_ERROR.getMsg());
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_ERROR);
        }

        //获取验证码
        String code = MyCaptchaUtil.getCaptcha(6);

        //发送短信验证码
        //模板参数为{"code":"xxxxxx"}需要转换成json字符串
        Map<String,String> map = new HashMap<String,String>();
        map.put("code",code);

        smsUtil.sendMessage(VERIFICATION_TEMPLATE_CODE,phoneNumber
                , JacksonUtil.writeValueAsString(map));

        //存储在redis,过期时间为60s.
        redisUtil.setTimeout(VERIFICATION_CODE_PREFIX+phoneNumber,code
                ,VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //校验手机号是否有效
        if(!RegexUtil.checkMobile(phoneNumber)) {
            logger.error(ServiceErrorCodeConstants.PASSWORD_ERROR.getMsg());
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
